package com.jrew.gae.stacktracer.services;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import com.jrew.gae.stacktracer.entities.Record;
import com.jrew.gae.stacktracer.exceptions.RecordNotExistException;
import com.jrew.gae.stacktracer.exceptions.RecordWrongPasswordException;
import com.jrew.gae.util.EntityManagerFactoryStorage;
import com.jrew.gae.util.RandomPassword;

/**
 *
 */
public class RecordManagerService {
	
	private EntityManagerFactory emFactory;
	
	public RecordManagerService() {
		emFactory = EntityManagerFactoryStorage.getInstance();
	}
	
	/**
	 * @param recordContent
	 * @return
	 */
	public Record addNewRecordService(String recordContent){
		Record newRecord = new Record(recordContent);
		newRecord.setPassword(RandomPassword.getRandomString());
		EntityManager entityManager = emFactory.createEntityManager(); 
		entityManager.persist(newRecord);
		entityManager.close();
		return newRecord;
	}
	
	/**
	 * @param id
	 * @return
	 */
	public Record getRecord(Long id, String password) throws RecordNotExistException, RecordWrongPasswordException {
		EntityManager entityManager = emFactory.createEntityManager();
		Record record = entityManager.find(Record.class, id);
		entityManager.close();
		if(record != null){
			String recordPassword = record.getPassword();
			if(recordPassword.equalsIgnoreCase(password)){
				return record;
			} else {
				throw new RecordWrongPasswordException();
			}
		} 
		throw new RecordNotExistException();
	}
	
}
